﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AukcjeInternetowe.Models;
using AukcjeInternetowe.Providers;

namespace AukcjeInternetowe.Controllers
{
    public class CategoriesController : Controller
    {
        public static OracleDataProvider db = new OracleDataProvider();
        public static List<Category> _categories = null;
        public static List<Category> Categories
        {
            get
            {
                if(_categories == null)
                {
                    _categories = db.GetCategories();
                }
                return _categories;
            }
        }

        private static String renderCategory(Category c)
        {
            return String.Format("<li><a href=\"/Categories/GetItems?id={0}\" alt=\"{1}\">{2}</a></li>",
                                    c.CategoryId,
                                    c.CategoryDescription,
                                    c.CategoryName);
        }
        //
        // GET: /Categories/

        public ContentResult Index()
        {
            string result = "<ul>";
            foreach(Category c in Categories)
            {
                result += renderCategory(c);
            }
            result += "</ul>";
            return Content(result);
        }

        public ActionResult GetItems(int? id)
        {
            Category c = (id.HasValue ? Categories.FirstOrDefault(cat => cat.CategoryId == id.Value) : null);

            //render category
            List<ItemCategoryModel> items = new List<ItemCategoryModel>();
            using (IDataProvider dataSource = new OracleDataProvider())
            {
                if (id.HasValue)
                    items = dataSource.GetItemsForCategory(id.Value);
                else
                    items = dataSource.GetAllItems();
            }

            return View("CategoryItemList", new CategoryViewData()
            {
                Category = c,
                CategoryItems = items
            });
        }
    }
}
